package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.view.Window;

import com.google.gson.Gson;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.callback.HandlerCallback;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.entity.MessageCountBean;
import com.sczmgk.hotline_pzh.fragment.MainHomeFragment;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.jpush.JpushObserver;
import com.sczmgk.hotline_pzh.jpush.MainHomeDataObserver;
import com.sczmgk.hotline_pzh.jpush.UIObserver;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.MyToast;

import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends FragmentActivity implements Observer {

    public static final int REQUEST_CODE_LOGIN = 201;

    /**
     * 主页区域选择
     */
    private HandlerCallback handlerCallback;
    private final String TAG = MainActivity.class.getSimpleName();
    private FragmentManager fragmentManager;

    private MainHomeFragment mainHomeFragment;

    protected Handler mHandler = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.main_container);//设置主页容器
        JpushObserver.getInstance().addObserver(this);
        initFregment();
        initHandler();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (CacheUtils.getBooleanData(MainActivity.this, Constants.IS_LOGIN_KEY, false)) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    initMessageData();
                }
            }, 500);
        }
    }

    private void initMessageData() {

        Map<String, Object> infos = new HashMap<>();
        infos.put("userid", CacheUtils.getIntData(this, Constants.LOGIN_UID, 0));
        infos.put("imei", MyApp.imei);

        MyHttp.requestByCommon(Constants.BASE_URL + Constants.GET_MY_MESSAGE_NUM_URL, infos, MyHttp.GET, MainActivity.this, false, null, new SimplePaserJsonCallback() {

            @Override
            public void onVerifyIsNull() {

            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
                paserDataJson(dataRaw, isCache);
            }

        });
    }

    private void paserDataJson(String dataRaw, boolean isCache) {
        Gson gson = new Gson();
        MessageCountBean messageCountBean = gson.fromJson(dataRaw, MessageCountBean.class);

        UIObserver.getInstance().hasNewMes(messageCountBean);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initFregment() {

        fragmentManager = getSupportFragmentManager();
        mainHomeFragment = new MainHomeFragment();
        fragmentManager.beginTransaction().replace(R.id.fl_main_container, mainHomeFragment).commit();
    }

    private void initHandler() {

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                MyLog.i(TAG, "MainActivity   收到消息！");
                if (handlerCallback != null) {
                    MyLog.d(TAG, "MainActivity   开始分发消息");
                    handlerCallback.onHandleMessage(msg);
                } else {
                    MyLog.e(TAG, "MainActivity   消息回调接口没有实现！");
                }
            }
        };
    }

    public void setHandlerCallback(HandlerCallback mainHomeHandlerCallback) {
        this.handlerCallback = mainHomeHandlerCallback;
    }

    /**
     * 取得Maihome的Hander
     *
     * @return
     */
    public Handler getmHandler() {
        return mHandler;
    }

    private boolean isFirstBack = true;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if (keyCode == KeyEvent.KEYCODE_BACK) {

            //处理返回键
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isFirstBack = true;
                }
            }, 2000);
            if (isFirstBack) {
                MyLog.d(TAG, " 第一次按 Back   isFirstBack:" + isFirstBack);

                isFirstBack = false;
                MyToast.show(MainActivity.this, getString(R.string.main_goback_hint));
                return true;
            } else {

                MyLog.d(TAG, " -----------第二次按 Back   isFirstBack:" + isFirstBack);
//                    setAlias("android_xx");
                return super.onKeyDown(keyCode, event);
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    @Override
    public void update(Observable observable, Object o) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MainHomeDataObserver.getInstance().hasNewMes(true);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_LOGIN:

                    boolean isLogin = CacheUtils.getBooleanData(MainActivity.this, Constants.IS_LOGIN_KEY, false);
                    if (!isLogin) {
                        //用户未登录
                        mainHomeFragment.goToMainHome();
                    }
                    MyLog.d(TAG, "用户登录成功，加载主页数据");
//                    mHandler.sendEmptyMessage(MainHomeApplication.REREQUEST_MAINHOME_DATA);
                    break;
                case Constants.ONLINE_COMPLAINT_REQUEST_CODE:
                    int complaint = data.getIntExtra(Constants.ONLINE_COMPLAINT_FLAG_NAME, 0);
                    mainHomeFragment.setComplaintFlag(complaint);
                    mainHomeFragment.goToComplaintSetting();
                    break;
                case Constants.COMPLAINT_REQUEST_CODE:
                    //取消投诉,评价成功后需要访问网络
                    mHandler.sendEmptyMessage(Constants.CHECK_COMPLAINT_VIEW);
                    break;
                case Constants.REQUEST_CODE_CHANGE_PWD:
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_LOGIN);
                    break;
            }
        }

    }
}

